/*
 * Copyright (c) 2025 DuckDuckGo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.duckduckgo.sync.impl.metrics

import com.duckduckgo.app.di.AppCoroutineScope
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.sync.impl.ConnectedDevice
import com.squareup.anvil.annotations.ContributesBinding
import dagger.SingleInstanceIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

interface ConnectedDevicesObserver {
    fun onDevicesUpdated(devices: List<ConnectedDevice>)
    fun observeConnectedDevicesCount(): StateFlow<Int>
}

@ContributesBinding(AppScope::class)
@SingleInstanceIn(AppScope::class)
class SyncConnectedDevicesObserver @Inject constructor(
    @AppCoroutineScope private val appCoroutineScope: CoroutineScope,
    private val dispatcherProvider: DispatcherProvider,
) : ConnectedDevicesObserver {

    private val _connectedDevicesCount = MutableStateFlow(0)
    override fun observeConnectedDevicesCount(): StateFlow<Int> = _connectedDevicesCount.asStateFlow()

    override fun onDevicesUpdated(devices: List<ConnectedDevice>) {
        appCoroutineScope.launch(dispatcherProvider.io()) {
            _connectedDevicesCount.emit(devices.size)
        }
    }
}
